package work.vcloud.baseinfo.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileUtil {

	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception { 
        File targetFile = new File(filePath);  
        if(!targetFile.exists()){    
            targetFile.mkdirs();    
        }       
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }
	
	public static void uploadFile(File file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        byte[] buffer = new byte[1024];
        BufferedOutputStream os = new BufferedOutputStream(
                new FileOutputStream(targetFile+"/"+fileName));
        int length = 0;
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
        while ((length = in.read(buffer)) != -1) {
            os.write(buffer, 0, length);
        }
        os.flush();
        os.close();
    }
	
	public static File createFile(String filePath, String fileName) throws Exception { 
        File targetFile = new File(filePath);  
        if(!targetFile.exists()){    
            targetFile.mkdirs();    
        }       
        File file = new File(filePath+fileName);
        return file;
    }
	
	/**
     *@title  获取文件后缀名
     *
     * @param filename
     * @return
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }
    
    public static boolean deleteFile(String fileName) {
	    File file = new File(fileName);
	    if(file.exists() && file.isFile()) {
		    if(file.delete()) {
		    	return true;
		    } else {
		    	return false;
		    }
	    } else {
	    	return false;
	    }
    }
	
}
